<template>
    <div>
        <van-nav-bar title="修改地址" left-text="返回" left-arrow @click-left="proxy.$leftClick()" />
        <van-address-edit 
        :area-list="areaList" 
        show-delete 
        show-set-default 
        show-search-result
        :search-result="searchResult" 
        :address-info="res"
        :area-columns-placeholder="[res.province, res.city,res.county]" 
        @delete="onDete"
        @save="onSave"/>
    </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref,onMounted } from 'vue';
import { areaList } from '@vant/area-data';
import { useRess } from '@/store/ress';
import type { AddressEditInfo,AddressEditSearchItem } from 'vant';
import { useRouter,useRoute} from 'vue-router';
const router = useRouter();
const route = useRoute();

const { proxy }: any = getCurrentInstance()

type k = keyof AddressEditInfo

// 定义地址的pinia
const store = useRess();

let searchResult = ref<AddressEditSearchItem[]>([]);

// 定义地址详细的容器 ress
let res = ref<ress>({} as ress)

// 当点击保存时
let onSave =async (info:AddressEditInfo)=>{
    // 调用地址pinia的更新接口方法
    await store.fetchUpdateRess(route.params.id as string,info)
    // 跳转到地址列表页面
    router.push({name:'set'})
}

// 当点击删除时
const onDete = async(i:AddressEditInfo)=>{
    // 调用地址pinia的删除接口
    await store.removes(route.params.id as string)
    // 跳转到地址列表
    router.push({name:"set"})
}

// 当页面渲染完成以后
onMounted(async()=>{
    // 在地址pinia中找到符合id的地址信息
    let data = store.ressData.find(item=>item.addressid == route.params.id)
    // 如果不存在 防止在修改地址页面刷新
    if(!data){
        // 跳转到地址列表页面
        router.push({name:'my'})
    }else{
        // 设置当前修改地址的容器信息
        res.value = data
    }
})
</script>